<template>
  <a-modal
    :title="isShow ? '修改' : '新建'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
    okText="确定"
    cancelText="取消"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="分类名称">
          <a-input
            v-decorator="['name', {rules: [{required: true, message: '请填写分类名称'}]}]" 
            placeholder="请填写分类名称"
          />
        </a-form-item>
        <a-form-item label="排序">
          <a-input
            v-decorator="['sort', {rules: [{required: true, message: '请填写分类排序'},
            {
              pattern:this.$reg.digit,
              message: '请填写数字',
            }]}]" 
            placeholder="请填写分类排序"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 表单字段
const fields = ['id', 'name', 'sort']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  components: {
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      isShow: false,
      form: this.$form.createForm(this)
    }
  },
  created () {
    console.log('custom modal created')
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      console.log('modal $watch',this.model)
      if(this.model && this.model.id > 0) {
        this.isShow = true
      } else {
        this.isShow = false
      }
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted() {
  },
  methods: {
    // 搜素模糊查询
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
  }
}
</script>
<style scoped>

</style>
